<script lang="ts" setup>
import { onMounted, ref, watch, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useDialogStore } from '../store/dialog'
import classification from '../api/classification'
import { status, StateProtect } from '../utils/classificationType'
import descrition from './descrition.vue'
import uploadImg from './uploadImg.vue'
import UploadImg from '../api/uploadImg.ts'
import utils from '../utils/utils'
import collection from '../api/collection.js'
import era from '../components/utils/era.vue'
import { useImgStore } from '../store/img'
import { useEraStore } from '../store/era.ts'
//获取修改藏品的信息
const dialogStore = useDialogStore()
const imgStore = useImgStore()
const eraStore = useEraStore()
// 在父组件中添加
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
//const ruleForm = ref<Record<string, any>>({})
const Classification = ref<TreeNode[]>([])
const treeSelectRef = ref()
// 修改定义处，显式声明类型
const defaultExpandedKeys = ref<(number | string)[]>([])
const rules: FormRules = {
  internalId: [
    { required: true, message: '请输入馆内编号', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1到50个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入藏品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在1到100个字符之间', trigger: 'blur' }
  ],
  alternateName: [
    { min: 0, max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  classificationId: [
    { required: true, message: '请选择藏品分类', trigger: 'change' }
  ],
  preservationStatus: [
    { required: true, message: '请选择保存状态', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择当前状态', trigger: 'change' }
  ],
  weight: [
    { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的重量数值', trigger: 'blur' }
  ],
  currentLocation: [
    { required: true, message: '请输入存放位置', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在1到200个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: '描述不能超过1000个字符', trigger: 'blur' }
  ]
}
interface TreeNode {
    value: number | string;
    label: string;
    children?: TreeNode[];
}
let abortController: AbortController | null = null // 请求中止控制器
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    if (loading.value) return
    loading.value = true
    formEl.validate(async (valid) => {
        abortController = new AbortController()
        if (valid) {
            dialogStore.setIsSubmit(true)
            try {
                if (imgStore.imgRow && imgStore.imgVisable) {
                    // 先执行上传
                    const response = await UploadImg.uploadImg(imgStore.imgRow, {
                        signal: abortController.signal // 绑定中止信号
                    })
                    if (response.data.code === 200) {
                        // 先设置数据再关闭对话框
                        dialogStore.contain.img = response.data.data
                        imgStore.setImgRowNull()
                        imgStore.imgUrl = ''
                    }
                }
                await classification.getSpecifiaId(dialogStore.contain.classificationId).then((res) => {
                    dialogStore.contain.classificationId = res.data.data
                })
                dialogStore.contain.updatedAt = utils.getCurrentTime()
                dialogStore.contain.eraId = Number(eraStore.value)
                console.log(dialogStore.contain)
                await collection.updateCollection(dialogStore.contain).then((res) => {
                    if(res.data.code === 200){
                        utils.showMessage('修改成功', "success", 2000)
                    }
                })
                dialogStore.setDialog()
            } catch (error) {
            } finally {
                loading.value = false
                abortController = null
                imgStore.setImgUrlNull()
                dialogStore.setContainNull()
                setTimeout(() => {
                    dialogStore.setIsSubmit(false) // 确保最终重置状态
                }, 500)
            }
        } else {
            console.log('error submit!')
        }
    })
}
function quxiao() {
    dialogStore.setDialog()
    imgStore.setImgVisable(false)
    imgStore.setImgUrlNull()
    console.log(imgStore.imgUrl)
    dialogStore.setContainNull()
    console.log(dialogStore.contain)
}
// 父组件逻辑
const handleDialogClosed = () => {
    // 重置上传相关状态
    imgStore.setImgRowNull()
}
// 对话框关闭时终止未完成的上传
const handleDialogClose = (done: () => void) => {
    imgStore.setImgRowNull() // 清空已选文件
    imgStore.setImgUrlNull()
    // 同时更新状态管理中的 dialog 状态
    dialogStore.setDialog()
    dialogStore.setContainNull()
    // 必须调用 done() 才能关闭对话框
    done()
}
function findParentIds(tree: TreeNode[], targetId: number | string, path: (number | string)[] = []): (number | string)[] | null {
    for (const node of tree) {
        if (node.value === targetId) {
            return path;
        }
        if (node.children) {
            const found = findParentIds(node.children, targetId, [...path, node.value]);
            if (found) return found;
        }
    }
    return null;
}
function handleVisibleChange(visible) {
    if (visible && dialogStore.contain.classificationId) {
        defaultExpandedKeys.value = findParentIds(Classification.value, dialogStore.contain.classificationId) || []
    }
}
onMounted(async () => {
    await classification.getClassification().then((res) => {
        Classification.value = res.data.data
    })
    eraStore.setValue(dialogStore.contain.eraId?.toString() || '')
})



</script>
<template>
    <el-dialog :destroy-on-close="false" v-model="dialogStore.dialog" title="藏品编辑" width="1000" class="edit-dialog"
        align-center @closed="handleDialogClosed" :before-close="handleDialogClose">
        <el-form ref="ruleFormRef" :model="dialogStore.contain" status-icon :rules="rules" label-width="100px"
            class="demo-ruleForm">
            <!-- 修改 el-row 的 gutter 为 20，并调整为三列 -->
            <el-row :gutter="20">
                <!-- 每列 span 改为 8 -->
                <el-col :span="8">
                    <el-form-item label="馆内编号" prop="internalId">
                        <el-input v-model="dialogStore.contain.internalId" class="edit-input" />
                    </el-form-item>
                    <el-form-item label="藏品名称" prop="name">
                        <el-input v-model="dialogStore.contain.name" class="edit-input" />
                    </el-form-item>
                    <el-form-item label="藏品别名" prop="alternateName">
                        <el-input v-model="dialogStore.contain.alternateName" class="edit-input" />
                    </el-form-item>
                    <el-form-item label="分类" prop="classificationId">
                        <el-tree-select ref="treeSelectRef" v-model="dialogStore.contain.classificationId" :data="Classification"
                            class="edit-select" :props="{
                                value: 'value',
                                label: 'label',
                                children: 'children'
                            }" clearable check-strictly :default-expanded-keys="defaultExpandedKeys"
                            @visible-change="handleVisibleChange" />
                    </el-form-item>
                    <el-form-item label="年代" prop="period">
                        <era class="edit-input" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="保存状态" prop="preservationStatus">
                        <el-tree-select v-model="dialogStore.contain.preservationStatus" :data="StateProtect.StateProtect"
                            class="edit-select" clearable />
                    </el-form-item>
                    <el-form-item label="当前状态" prop="status">
                        <el-tree-select v-model="dialogStore.contain.status" :data="status.State" class="edit-select" clearable />
                    </el-form-item>
                    <el-form-item label="重量(kg)" prop="weight">
                        <el-input v-model="dialogStore.contain.weight" class="edit-input" />
                    </el-form-item>
                    <el-form-item label="存放位置" prop="currentLocation">
                        <el-input v-model="dialogStore.contain.currentLocation" class="edit-input" />
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                        <descrition :key="dialogStore.contain.internalId" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="图片上传">
                        <uploadImg v-if="dialogStore.dialog" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="dialog-footer">
            <el-button @click="quxiao">取消</el-button>
            <el-button type="primary" :loading="loading" @click="submitForm(ruleFormRef)">提交</el-button>
        </div>
    </el-dialog>
</template>

<style scoped>
.edit-dialog {
    .el-form-item {
        margin-bottom: 20px;

        :deep(.el-form-item__label) {
            font-weight: 600;
            color: #606266;
        }
    }

    .original-info {
        font-size: 12px;
        color: #909399;
        background: #f5f7fa;
        padding: 6px 10px;
        border-radius: 4px;
        margin-bottom: 8px;
        line-height: 1.4;

        &.text-ellipsis {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    .edit-input {
        width: 100%;

        :deep(.el-input__inner) {
            border-radius: 4px;
            transition: all 0.3s;

            &:hover {
                border-color: #409eff;
            }
        }
    }

    .edit-select {
        width: 100%;

        :deep(.el-select__wrapper) {
            border-radius: 4px;
        }
    }

    .edit-textarea {
        :deep(.el-textarea__inner) {
            border-radius: 4px;
            resize: vertical;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        padding-top: 20px;
        border-top: 1px solid #ebeef5;
    }
}

.edit-dialog {
    :deep(.el-dialog__body) {
        padding: 20px;
    }

    .demo-ruleForm {
        max-width: none !important;
    }

    .el-row {
        margin-bottom: -20px;
    }

    .edit-input,
    .edit-select {
        width: 100%;
    }

    /* 调整树选择器样式 */
    .el-tree-select {
        :deep(.el-select__wrapper) {
            width: 100%;
        }
    }

    /* 图片上传组件样式 */
    .uploadImg {
        margin-top: 8px;
    }
}
</style>
